#!/usr/bin/env python
#coding=gbk
from mutagen.easyid3 import EasyID3
from mutagen.mp3 import MP3
from mutagen.id3 import TCON
from pprint import pprint
import re
import sys
import mutagen


def getItem(value):
    xx=value
    try:
        temp=xx.encode("GBK")
    except:
        try:
            xx=tryCorrectCodec(xx)
        except:
            xx=u""
    return xx


def saveinfo(name):
##    print name
    audio = MP3(name, ID3=EasyID3)

    for i in audio.iteritems():
        audio[i[0]]=getItem(i[1][0])
    sqlstr="insert  into music values (?,?,?,?)"

    try:
        title=audio['title'][0]
    except KeyError,e:
        print e
        title=unicode("None")
    try:
        artist=audio['artist'][0]
    except KeyError,e:
        print e
        artist=unicode("None")
    try:
        album=audio['album'][0]
    except KeyError,e:
        print e
        album=unicode("None2")

    t=[name,title,artist,album]
    ##.encode("GBK")

    curr.execute(sqlstr,t)
    if curr.rowcount ==0:
        print name,curr.rowcount

import sqlite3
conn = sqlite3.connect("./mp3.sqlite")
curr=conn.cursor()
conn.execute("create table if not exists music(filename varchar(256) primary key, title varchar(128), artist varchar(128), album varchar(128))")
conn.execute("DELETE FROM  music")
saveinfo(u"G:\\KuGou\\Rain - Love Story.mp3")


def file2id3(name):
    pass
##import os,sys
##path="g:\\KuGou\\"
##for root, dirs, files in os.walk(path):
##  for file in files:
##    match=re.match(".*\.mp3",file)
##    if match:
##        #print "-----------------"
##        path=os.path.join(root, file)
##        if type(path)==type("str"):
##            path=path.decode("GBK")
##            try:
##                id3v2_to_id3v1(path,"GBK")
##            except ID3NoHeaderError,e:
##                print path
##                pprint(e)
##                file2id3(file)

##        saveinfo(path)




curr.close()
conn.commit()
conn.close()